package com.quanyan.stadium.component.pushMsg;

import com.alibaba.fastjson.JSON;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.messagepush.entity.*;
import com.quanyan.messagepush.enums.BoxName;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.messagepush.enums.MsgType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.Arrays;

/**
 * Created by xiaoxiao on 16/7/14.
 */
@Component("stadiumMsgPush")
public class MsgPush {

    @Value("${message.push.service.url}")
    private String messagePushServiceUrl;

    private final static Logger logger = LoggerFactory.getLogger(MsgPush.class);

    private final static String DEFAULT_VAR = "变量";

    private final static String XXX_VAR = "XXX";

    /**
     * 消息body类型
     */
    public final static int PARAMETER = 0;
    public final static int PARAMETERVALUE = 1;
    public final static int REPLACEXXX = 2;
    public final static int REPLACEFIRSTXXX = 3;


    /**
     * 消息的key定义, 与数据库一致
     *
     * */
    public final static String USER_GAME_PK_LAUNCH_MSG = "USER_GAME_PK_LAUNCH_MSG";
    public final static String CLUB_GAME_PK_LAUNCH_MSG = "CLUB_GAME_PK_LAUNCH_MSG";
    public final static String GAME_PK_AGREE_MSG = "GAME_PK_AGREE_MSG";
    public final static String GAME_PK_REFUSE_MSG = "GAME_PK_REFUSE_MSG";
    public final static String GAME_OFFICIAL_JOIN_MSG = "GAME_OFFICIAL_JOIN_MSG";
    public final static String GAME_OFFICIAL_JOIN_QUALIFICATION_MSG = "GAME_OFFICIAL_JOIN_QUALIFICATION_MSG";
    public final static String GAME_OFFICIAL_SCHEDULE_END_MSG = "GAME_OFFICIAL_SCHEDULE_END_MSG";     //用户参加的赛程结束
    public final static String GAME_OFFICIAL_RECORD_DISPUTE_MSG = "GAME_OFFICIAL_RECORD_DISPUTE_MSG";        //录入结果存在争议
    public final static String GAME_OFFICIAL_SCHEDULE_LIST_GENERATE_MSG = "GAME_OFFICIAL_SCHEDULE_LIST_GENERATE_MSG"; //对战表生成
    public final static String GAME_OFFICIAL_SCHEDULE_USER_WIN_MSG = "GAME_OFFICIAL_SCHEDULE_USER_WIN_MSG";   //晋级用户
    public final static String GAME_OFFICIAL_SCHEDULE_USER_FAIL_MSG = "GAME_OFFICIAL_SCHEDULE_USER_FAIL_MSG"; //未晋级用户
    public final static String GAME_OFFICIAL_EVENT_SHARE_MSG = "GAME_OFFICIAL_EVENT_SHARE_MSG";
    public final static String GAME_OFFICIAL_EVENT_SHARE_URL = "GAME_OFFICIAL_EVENT_SHARE_URL";
    public final static String GAME_SCENE_EVENT_RANK_LIST_SHARE_URL = "GAME_SCENE_EVENT_RANK_LIST_SHARE_URL";   //现场编排赛排行榜
    public final static String GAME_SCENE_EVENT_INTERNAL_DETAIL_SHARE_URL = "GAME_SCENE_EVENT_INTERNAL_DETAIL_SHARE_URL";   //内部赛详情


    public final static String GAME_OFFICIAL_EVENT_CANCEL_MSG = "GAME_OFFICIAL_EVENT_CANCEL_MSG";     //赛事取消
    public final static String GAME_OFFICIAL_EVENT_EDN_MSG = "GAME_OFFICIAL_EVENT_EDN_MSG";           //赛事结束
    public final static String GAME_OFFICIAL_TEAM_PERSON_TOP1_MSG = "GAME_OFFICIAL_TEAM_PERSON_TOP1_MSG";
    public final static String GAME_OFFICIAL_TEAM_PERSON_TOP2_MSG = "GAME_OFFICIAL_TEAM_PERSON_TOP2_MSG";
    public final static String GAME_OFFICIAL_TEAM_CLUB_TOP1_MSG = "GAME_OFFICIAL_TEAM_CLUB_TOP1_MSG";
    public final static String GAME_OFFICIAL_TEAM_CLUB_TOP2_MSG = "GAME_OFFICIAL_EVENT_SHARE_MSG";
    public final static String GAME_OFFICIAL_TEAM_PERSON_START_MSG = "GAME_OFFICIAL_TEAM_PERSON_START_MSG";
    public final static String GAME_OFFICIAL_TEAM_CLUB_START_MSG = "GAME_OFFICIAL_TEAM_CLUB_START_MSG";
    public final static String GAME_OFFICIAL_TEAM_PERSON_SCHEDULE_ONE_HOUR_START_MSG = "GAME_OFFICIAL_TEAM_PERSON_SCHEDULE_ONE_HOUR_START_MSG";
    public final static String GAME_OFFICIAL_TEAM_CLUB_SCHEDULE_ONE_HOUR_START_MSG = "GAME_OFFICIAL_TEAM_CLUB_SCHEDULE_ONE_HOUR_START_MSG";

    public final static String GAME_EXPIRE_TIME_MSG = "GAME_EXPIRE_TIME_MSG";
    public final static String GAME_EXPIRED_TIME_MSG = "GAME_EXPIRED_TIME_MSG";
    public final static String GAME_DOUBLE_INVITE_USER = "GAME_DOUBLE_INVITE_USER";



    public final static String GAME_SCORE_DISAGREE = "GAME_SCORE_DISAGREE";
    public final static String GAME_NEW_SIGN_USER = "GAME_NEW_SIGN_USER";
    public final static String GAME_FINISH = "GAME_FINISH";
    public final static String GAME_BEFORE_1_HOUR = "GAME_BEFORE_1_HOUR";
    public final static String GAME_SHUT_UP = "GAME_SHUT_UP";
    public final static String GAME_NEAR_OFF = "GAME_NEAR_OFF";
    public final static String GAME_IS_OFF = "GAME_IS_OFF";
    public final static String GAME_INPUT_SCORE = "GAME_INPUT_SCORE";
    public final static String GAME_VITIATION_SCORE = "GAME_VITIATION_SCORE";
    public final static String GAME__UNNORMAL_END = "GAME__UNNORMAL_END";












    /**
     * 定义一些消息推送时,跳转的路径,注意该路径必须存在
     *
     * */
    public final static String USER_GAME_SCHEDULE_URL = "/api/stadium/gameEvent/gameEventList";

    public final static String GAME_SIGN_SUCCESS_URL = "/api/stadium/gameSignUp/getUserOrder";


    /**
     *  简单封装消息推送
     *
     * */
    @Async
    public void pushMessageOperate(StadiumMsgModel stadiumMsgModel) {

        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.RACE.value()+"_" + System.currentTimeMillis());

        //定义消息的标题和body
        Alert alert = new Alert();
        alert.setTitle(stadiumMsgModel.getAlertTitle());
        alert.setBody(stadiumMsgModel.getAlertBody());

        //消息盒子
        Payload payload = new Payload();
        payload.setTitle(stadiumMsgModel.getMsgTitle());
        payload.setBoxType(BoxType.COMPETITION_MSG.value());
        payload.setMsgType(stadiumMsgModel.getMsgType().value());
        payload.setUrl(stadiumMsgModel.getToUrl());
        payload.setTimestamp(System.currentTimeMillis());
        payload.setBody(stadiumMsgModel.getMsgBody());

        if (stadiumMsgModel.getMsgType().value() == MsgType.JUMP_MSG.value()) {
            //跳转的页面, params有效 id已经失效
            Jump jump = new Jump();
            jump.setIdType(stadiumMsgModel.getIdType().value());
            jump.setId(stadiumMsgModel.getToId());
            jump.setParam(stadiumMsgModel.getParams());
            payload.setJump(jump);
        }

        //消息封装
        pushMessage.setAlert(alert);
        pushMessage.setTo(stadiumMsgModel.getToUidList());
        pushMessage.setLogo("");
        pushMessage.setLogoUrl("");
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));
        try {
            String postJson = JSON.toJSONString(reqPushMessage);
            String result = HttpClientUtils.postJson(messagePushServiceUrl, postJson);
            logger.info("运动场消息推送,内容:{},返回状态:{}", postJson, result);
        } catch (Exception e) {
            logger.error("推送消息失败，原因:{}", e);
        }
    }

    /**
     * 替换模板里的变量.替换  你好,变量 为 你好,潇潇,注意必须为中文,字符
     *
     * */
    public static String msgUtils(String body, final String ...params) {
        if (params!=null && params.length > 0) {
            for (String str: params) {
                if (!StringUtils.isEmpty(str)) {
                    body = body.replaceFirst(DEFAULT_VAR, str);
                }
            }
        }
        return body;
    }

    /**
     * 替换模板中的xxx
     * @param body
     * @param param
     * @return
     */
    public static String msgUtilsReplaceXXX(String body, final String param) {
        body = body.replace(XXX_VAR, param);
        return body;
    }

    public static String msgUtilsReplaceFirstXXX(String body, final String param) {
        body = body.replaceFirst(XXX_VAR, param);
        return body;
    }
}

